package com.iversonx.observer.example_1.v2;

import com.iversonx.observer.example_1.v2.listener.EventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 **/
public class EventManager {
    private final Map<EventType, List<EventListener>> listenerMap = new ConcurrentHashMap<>();
    public EventManager() {
        listenerMap.put(EventType.MQ, new ArrayList<>());
        listenerMap.put(EventType.SMS, new ArrayList<>());
    }
    
    public void subscribe(EventType eventType, EventListener listener) {
        List<EventListener> users = listenerMap.get(eventType);
        users.add(listener);
    }
    
    public void notifyMQEvent(String msg) {
        notifyEvent(msg, EventType.MQ);
    }
    
    public void notifySmsEvent(String msg) {
        notifyEvent(msg, EventType.SMS);
    }
    
    private void notifyEvent(String msg, EventType eventType) {
        List<EventListener> listeners = listenerMap.get(eventType);
        if(listeners != null && !listeners.isEmpty()) {
            for(EventListener listener : listeners) {
                listener.doEvent(msg);
            }
        }
    }
    
    public enum EventType {
        MQ, SMS
    }
}
